// // 仿后端数据，来自localStorage
// const trainingData = JSON.parse(localStorage.getItem("trainingData"));
const trainingData = [
  {
    trainingId: "0",
    isSelected: false,
    trainingTitle: "2021新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-03",
    endDate: "2022-01-04",
    numOfStudent: 10,
    trainingRange: "全部成员",
    trainingIntro: "",
    isFinished: true,
  },
  {
    trainingId: "1",
    isSelected: false,
    trainingTitle: "2020新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-13",
    endDate: "2022-01-24",
    numOfStudent: 12,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "2",
    isSelected: false,
    trainingTitle: "办公技能培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "EXCEL培训",
    startDate: "2022-01-13",
    endDate: "2022-01-14",
    numOfStudent: 13,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "3",
    isSelected: false,
    trainingTitle: "2018新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-03",
    endDate: "2022-01-04",
    numOfStudent: 14,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "4",
    isSelected: false,
    trainingTitle: "2017新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-03",
    endDate: "2022-01-04",
    numOfStudent: 15,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "5",
    isSelected: false,
    trainingTitle: "2021新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2021-01-03",
    endDate: "2021-01-04",
    numOfStudent: 16,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "6",
    isSelected: false,
    trainingTitle: "2015新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-03",
    endDate: "2022-01-04",
    numOfStudent: 17,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "7",
    isSelected: false,
    trainingTitle: "2021新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-01",
    endDate: "2022-09-01",
    numOfStudent: 18,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
  {
    trainingId: "8",
    isSelected: false,
    trainingTitle: "2021新员工入职培训",
    coverImage: "../resource-lxr/images/04.png",
    trainingCategory: "入职培训",
    startDate: "2022-01-01",
    endDate: "2022-09-01",
    numOfStudent: 19,
    trainingRange: "指定成员",
    trainingIntro: "",
    isFinished: false,
  },
];
// 表单验证规则
const rules = {
  // 必填
  courseTitle: {
    tips: "请输入培训计划名称",
    contentReg: /^\s*$/,
    contentErrorMessage: "请输入培训计划名称",
    sizeReg: "",
    sizeErrorMessage: "",
  },
  // 必填
  coverImage: {
    tips: "请上传文件：支持png、jpg、jpeg等格式；大小不超过10mb",
    contentReg: /^(\s|\S)+(jpg|jpeg|png|JPG|PNG|JPEG)+$/,
    contentErrorMessage: "请检查文件格式是否为：png、jpg、jpeg等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
  // 必填
  courseCategory: {
    tips: "请选择课程分类",
    contentReg: /^\s*$/,
    contentErrorMessage: "请选择课程分类",
    sizeReg: "",
    sizeErrorMessage: "",
  },
  // 必填
  courseVideo: {
    tips: "请上传文件：支持mp4、m4v、aiv等格式；大小不超过10G",
    contentReg: /^(\s|\S)+(mp4|MP4|m4v|M4V|aiv|AIV)+$/,
    contentErrorMessage: "请检查文件格式是否为：mp4、m4v、aiv等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
  // 选填
  courseMaterial: {
    tips: "· 支持pdf、doc、docx、exl格式；大小不超过100mb",
    contentReg: /^(\s|\S)+(pdf|PDF|doc|DOC|docx|DOCX|exl|EXL)+$/,
    contentErrorMessage: "请检查文件格式是否为：pdf、doc、docx、exl等",
    sizeReg: /[\u4e00-\u9fa5]{2,}/,
    sizeErrorMessage: "文件大小不超过10mb",
  },
};
// 创建课程id
let index = 100;
function createId() {
  return ++index;
}
// const pageSize = 10;

// 1. 渲染表格
renderTable(trainingData);
// 2. 渲染分页

// 渲染表格函数
function renderTable(data, currentPage = 1) {
  const pageSize = parseInt($(".per-page").val());
  $(".box-body>table>tbody").empty();
  renderPage(data, currentPage);
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pageData = data.slice(startIndex, endIndex);

  for (let i = 0; i < pageData.length; ++i) {
    const checked = pageData[i].isSelected ? "checked" : "";
    const finished = pageData[i].isFinished ? "· 已完成" : "· 进行中";
    $(".box-body>table>tbody").append(`
    <tr>
    <td><input ${checked} class="select-box" type="checkbox"/></td>    
    <td>
      <div class="course-card">
        <div class="card-left">
          <div class="training-title">${pageData[i].trainingTitle}</div>
          <div class="training-category">分类：${pageData[i].trainingCategory}</div>
          <div class="training-time">
            培训计划时间：${pageData[i].startDate}~${pageData[i].endDate}
          </div>
        </div>
        <div class="card-right">
          <div class="card-right-up">
            <span class="training-plan">培训计划</span
            ><span class="training-status" >${finished}</span>
          </div>
          <div class="card-right-down">
            <span>培训人数：</span
            ><span class="student-num">${pageData[i].numOfStudent}</span
            ><span class="cut-off">|</span><span>课程：</span
            ><span class="course-num">3</span>
          </div>
          <div class="btn-box">
            <button type="button" class="btn btn-link" data-id="${pageData[i].trainingId}">
              查看详情</button
            ><button type="button" class="btn btn-link mod-time" data-id="${pageData[i].trainingId}" data-toggle="modal" data-target="#modTimeModal">
              调整时间</button
            ><button type="button" class="btn btn-link finished" data-id="${pageData[i].trainingId}" data-toggle="modal" data-target="#finishedModal">
              完成培训
            </button>
          </div>
        </div>
      </div>
    </td>
  </tr>`);
    // console.log(`${i}`, pageData[i].isFinished)
    //   if (pageData[i].isFinished) {
    //     $(".training-status").addClass("finished-red")
    //   }
  }
}
// 单独渲染一个模态框

// 渲染分页
function renderPage(data, currentPage = 1) {
  const pageSize = parseInt($(".per-page").val());
  $(".pagination").empty();
  const totalPages = Math.ceil(data.length / pageSize);
  $(".page>.pagination").append(`<li><a href="#" class="pre">&laquo;</a></li>`);
  for (let i = 0; i < totalPages; ++i) {
    $(".page>.pagination").append(`
                <li><a href="#" class="pageNum">${i + 1}</a></li>
        `);
  }
  $(".page>.pagination").append(
    `<li><a href="#" class="next">&raquo;</a></li>`
  );
  $(".page>.pagination>li").eq(currentPage).addClass("active");
}

// 选择pageSize
$(".per-page").on("change", function () {
  renderTable(trainingData);
});

// 点击页码切换页面
$(".page>.pagination").on("click", ".pageNum", function (event) {
  $(".pageNum").parent().removeClass("active");
  const currentPage = parseInt($(event.target).text());
  renderTable(trainingData, currentPage);
  $(event.target).parent().addClass("active");
});

// 点击上下页切换页面(!!!渲染上去的，事件委托！！！)
$(".page>.pagination").on("click", ".pre", function () {
  const currentPage = parseInt($(".active>a").text());
  const prePage = currentPage - 1;
  if (currentPage === 1) {
    return;
  }
  renderTable(trainingData, prePage);
});

// 点击 切换下一页
$(".page>.pagination").on("click", ".next", function () {
  const pageSize = parseInt($(".per-page").val());
  const currentPage = parseInt($(".active").text());
  const nextPage = currentPage + 1;
  const totalPages = Math.ceil(trainingData.length / pageSize);
  if (currentPage === totalPages) {
    return;
  }
  renderTable(trainingData, nextPage);
});

// 选择 全选
$(".table>tbody").on("change", ".select-box", function (event) {
  // 注意检验checked属性的方法
  const selected = $(event.target).prop("checked");
  const dataId = $(event.target).parent().parent().attr("data-id");
  for (let i = 0; i < trainingData.length; ++i) {
    if (dataId === trainingData[i].courseId) {
      trainingData[i].isSelected = selected;
    }
  }
  if (selected) {
    $(event.target).parent().parent().addClass("selected-item");
  } else {
    $(event.target).parent().parent().removeClass("selected-item");
  }
});
// 全选
$(".select-all>input").on("change", function (event) {
  const currentPage = parseInt($(".active>a").text());
  const selected = $(event.target).prop("checked");
  for (let i = 0; i < trainingData.length; ++i) {
    trainingData[i].isSelected = selected;
  }
  renderTable(trainingData, currentPage);
});

// 搜索？？？优化空间：多个课程标题的搜索
$(".search-btn").on("click", function () {
  $(".filter-box").empty();
  const searchCourseTitle = $(".search-course-title").val().trim();
  const searchStartDate = $(".search-start-date").val();
  const searchEndDate = $(".search-end-date").val();
  let searchRes = [];
  let startRes = [];
  let endRes = [];
  if (!searchCourseTitle && !searchStartDate && !searchEndDate) {
    return;
  } else {
    if (searchCourseTitle) {
      $(".filter-box").append(
        `<div class="title-condition"><span>培训名称：</span><span class="search-title">${searchCourseTitle}</span><span class="glyphicon glyphicon-remove"></span></div>`
      );
      const searchCondition = $(".title-condition>.search-title");
      console.log(`searchCondition.length`, searchCondition.length);
      const conditionArr = [];
      const newArr = [];
      for (let i = 0; i < searchCondition.length; ++i) {
        const conditionItem = searchCondition.eq(i).text();
        conditionArr.push(conditionItem);
      }
      // 数组去重
      arrayDeduplicate(conditionArr, newArr);
      console.log(`conditionArr`, conditionArr);
      for (let l = 0; l < newArr.length; ++l) {
        const conditionItem = newArr[l];
        for (let j = 0; j < trainingData.length; ++j) {
          const condition =
            trainingData[j].trainingTitle.includes(conditionItem);
          if (condition) {
            searchRes.push(trainingData[j]);
          }
        }
      }
    }
    // 日期搜索
    if (searchStartDate || searchEndDate) {
      $(".filter-box").append(
        `<div class="time-condition"><span>培训计划时间：</span><span class="search-title">${searchStartDate}~${searchEndDate}</span><span class="glyphicon glyphicon-remove"></span></div>`
      );
      // 开始时间

      for (let i = 0; i < searchRes.length; ++i) {
        if (!searchStartDate) {
          break;
        } else {
          const condition = searchRes[i].startDate >= searchStartDate;
          if (!condition) {
            searchRes.splice(i, 1);
            --i;
          }
        }
      }
      // 结束时间
      for (let i = 0; i < searchRes.length; ++i) {
        if (!searchEndDate) {
          break;
        } else {
          const condition = searchRes[i].endDate <= searchEndDate;
          if (!condition) {
            searchRes.splice(i, 1);
            --i;
          }
        }
      }
    }
    // 单独搜日期
    renderTable(searchRes);
  }
});

// 重置
$(".reset-btn").on("click", function () {
  $(".filter-box").empty();
  $(".search-course-title").val("");
  $(".search-start-date").val("");
  $(".search-end-date").val("");

  renderTable(trainingData);
});

// 点击 调整时间
// 1. 渲染 调整时间模态框
$(".box-body>table>tbody").on("click", ".mod-time", function (event) {
  // 先清空上一次渲染的模态框，保持页面内始终只有1个模态框
  $("#modalBox").empty();
  const dataId = $(event.target).attr("data-id");
  const currentTraining = trainingData.find(
    (item) => item.trainingId === dataId
  );
  $("#modalBox").append(`<!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="modTimeModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button
            type="button"
            class="close"
            data-dismiss="modal"
            aria-hidden="true"
          >
            &times;
          </button>
          <h4 class="modal-title" id="myModalLabel">培训计划时间调整</h4>
        </div>
        <div class="modal-body">
        <div>培训计划名称：${currentTraining.trainingTitle}</div>
            <!-- 培训开始时间 -->
            <div class="form-group mod-start-date">
              <label class="col-sm-1.5 control-label" for="inputSuccess"
                >培训开始时间：</label
              >
              <div class="col-sm-1.5">
                <input
                  type="date"
                  value="${currentTraining.startDate}"
                  name="startDate"
                  class="form-control"
                  id="startDate"
                /></div>                
                <label class="control-label col-sm-3 tips" for="inputCourseTitle"
                ></label>
            </div>
            <!-- 培训结束时间 -->
            <div class="form-group mod-end-date">
              <label class="col-sm-1.5 control-label" for="inputSuccess"
                >培训结束时间：</label
              >
              <div class="col-sm-1.5">
                <input
                  type="date"
                  value="${currentTraining.endDate}"
                  name="releaseTime"
                  class="form-control"
                  id="endDate"
                /></div>                
                <label class="control-label col-sm-3" for="inputCourseTitle"
                ></label>
            </div>
        </div>
        <div class="modal-footer">
          <button 
          id="delCancelBtn"
          type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="modConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id="${currentTraining.trainingId}"
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
});
// 2. 调整时间模态框 点击确认，更改时间
$(".box-body").on("click", "#modConfirmBtn", function (event) {
  // 检验 非空
  if (!$("#startDate").val()) {
    $(".mod-start-date").addClass("has-error");
    $(".mod-start-date>.tips").next().text("请选择日期");
    return;
  } else {
    $(".mod-start-date").removeClass("has-error");
  }
  if (!$("#endDate").val()) {
    $(".mod-end-date").addClass("has-error");
    $(".mod-end-date>.tips").next().text("请选择日期");
    return;
  } else {
    $(".mod-end-date").removeClass("has-error");
  }
  if ($("#startDate").val() > $("#endDate").val()) {
    $(".mod-start-date").addClass("has-error");
    $(".mod-end-date").addClass("has-error");
    return;
  }
  const currentPage = parseInt($(".active").text());
  const dataId = $(event.target).attr("data-id");
  for (let i = 0; i < trainingData.length; ++i) {
    if (trainingData[i].trainingId === dataId) {
      trainingData[i].startDate = $("#startDate").val();
      trainingData[i].endDate = $("#endDate").val();
    }
  }
  $("#modTimeModal").modal("hide");

  renderTable(trainingData, currentPage);
});

// 点击完成培训
// 1. 渲染 完成模态框
$(".box-body>table>tbody").on("click", ".finished", function (event) {
  // 先清空上一次渲染的模态框，保持页面内始终只有1个模态框
  $("#modalBox").empty();
  const dataId = $(event.target).attr("data-id");
  const currentTraining = trainingData.find(
    (item) => item.trainingId === dataId
  );
  if (currentTraining.isFinished) {
    return;
  }
  $("#modalBox").append(`<!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="finishedModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button
            type="button"
            class="close"
            data-dismiss="modal"
            aria-hidden="true"
          >
            &times;
          </button>
          <h4 class="modal-title" id="myModalLabel">确定该课程已完成？</h4>
        </div>
        <div class="modal-body">课程名称：${currentTraining.trainingTitle}</div>
        <div class="modal-footer">
          <button 
          id="delCancelBtn"
          type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="finishedConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id="${currentTraining.trainingId}"
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
});
// 2. 完成模态框 点击确认，删除数据
$(".box-body").on("click", "#finishedConfirmBtn", function (event) {
  $("#finishedModal").modal("hide");
  const currentPage = parseInt($(".active").text());
  const dataId = $(event.target).attr("data-id");
  trainingData.find((item) => {
    if (item.trainingId === dataId) {
      item.isFinished = true;
    }
  });
  renderTable(trainingData, currentPage);
});

// 点击 新增培训计划
// 1. 渲染 新增模态框
$(".add-btn").on("click", function (event) {
  $("#modalBox").empty();
  $("#modalBox").append(`    <!-- 模态框（Modal） -->
  <div
    class="modal fade"
    id="addModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="myModalLabel"
    aria-hidden="true"
    data-backdrop="static"
  >
    <div id="editArea" class="modal-dialog">
      <div id="editAreaContent" class="modal-content">
      <div class="modal-header">
      <button
        type="button"
        class="close"
        data-dismiss="modal"
        aria-hidden="true"
      >
        &times;
      </button>
      <h4 class="modal-title" id="myModalLabel"></h4>
    </div>
        <div id="editAreaContentBody" class="modal-body">
          <div class="edit-page">
            <div class="edit-page-box">
              <h2 id="subTitle">新增培训计划</h2>
              <form class="edit-content">

      <!-- 培训计划名称 -->
      <div class="form-group edit-course-title">
        <span class="star">*</span>
        <label class="col-sm-2 control-label"
          >培训计划名称：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="text"
            value=""
            name="courseTitle"
            placeholder="请输入"
            class="form-control"
            id="courseTitle"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"></label>    </div>

      </div>
      <!-- 上传封面图片 -->
      <div class="form-group edit-cover-image">
        <span class="star">*</span>
        <label class="col-sm-2 control-label" for="inputSuccess"
          >上传封面图片：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <input
            type="file"
            value=""
            name="coverImage"
            class="form-control"
            id="coverImage"
          />
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        >· 支持png、jpg、jpeg等格式；大小不超过10mb</label>
        </div>
      </div>
      <!-- 培训分类 -->
      <div class="form-group edit-course-category">
        <span class="star">*</span>
        <label class="col-sm-2 control-label" for="inputSuccess"
          >培训分类：</label
        >
        <div class="form-group col-sm-10">
        <div class="col-sm-4">
          <select
            name=""
            id="courseCategory"
            class="form-control"
            value=""
          >
            <option value="入职培训" selected>入职培训</option>
            <option value="办公技能培训">办公技能培训</option>
            <option value="市场培训" >市场培训</option></select>
        </div>
        <label class="control-label col-sm-7 tips" for="inputCourseTitle"
        ></label
      >
      </div>
      </div>
      <!-- 培训开始时间 -->
      <div class="form-group edit-release-time">
        <label class="col-sm-2 control-label" for="inputSuccess"
          >培训开始时间：</label
        >
        <div class="col-sm-4">
          <input
            type="date"
            value=""
            name="releaseTime"
            class="form-control"
            id="startDate"
          /></div>
          <label class="control-label col-sm-7 tips" for="inputCourseTitle"
          ></label
        >
      </div>
      <!-- 培训结束时间 -->
      <div class="form-group edit-release-time">
        <label class="col-sm-2 control-label" for="inputSuccess"
          >培训结束时间：</label
        >
        <div class="col-sm-4">
          <input
            type="date"
            value=""
            name="releaseTime"
            class="form-control"
            id="endDate"
          /></div>
          <label class="control-label col-sm-7 tips" for="inputCourseTitle"
          ></label
        >
      </div>
      <!-- 培训人数 -->
      <div class="form-group edit-release-time">
        <label class="col-sm-2 control-label" for="inputSuccess"
          >培训人数：</label
        >
        <div class="col-sm-4">
          <input
            type="number"
            value=""
            name="releaseTime"
            class="form-control"
            id="numOfStudent"
            placeholder="请输入"
          /></div>
          <label class="control-label col-sm-7 tips" for="inputCourseTitle"
          ></label
        >
      </div>
      <!-- 培训人群 -->
      <div class="form-group edit-visible-range">
      <label class="col-sm-2 control-label" for="inputSuccess"
      >培训人群：</label
    >
        <label class="radio-inline">
          <input
            type="radio"
            name="range"
            id="allVisible"
            value="全部成员"

          />全部成员
        </label>
        <label class="radio-inline">
          <input
            type="radio"
            name="range"
            id="designatedVisible"
            value="指定成员"
            checked
          />指定成员
        </label>
        <button id="selectMember"class="btn btn-link select-member" data-toggle="modal" data-target="#myModal">选择成员</button>
        <p class="help-block col-sm-5"></p>
      </div>
      <!-- 培训简介 -->
      <div class="form-group edit-course-intro">
      <label class="col-sm-2 control-label" for="inputSuccess"
      >培训简介：</label>
      <div class="col-sm-8 textarea-box">
        <img
          src="https://cdn3.axureshop.com/demo/2080033/images/%E6%96%B0%E5%A2%9E%E8%81%8C%E4%BD%8D_1/u8031.png"
        />
        <textarea
          name=""
          id="courseIntro"
          value=""
          cols="30"
          rows="10"
          class="form-control"
        ></textarea>
        </div>
      </div>
    </form>

            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            取消
          </button>
          <button
            id="addConfirmBtn"
            type="button"
            class="btn btn-primary"
            data-id=""
          >
            确定
          </button>
        </div>
      </div>
      <!-- /.modal-content -->
    </div>
    <!-- /.modal -->
  </div>`);
});
formValidation();
// 2. 新增模态框：点击确认==》填入内容==（修改）==》信息验证==》保存数据
$(".box-body").on("click", "#addConfirmBtn", function (event) {
  const currentPage = parseInt($(".active").text());
  // 验证
  formValidation();
  const eqLength = $(".edit-content>div>.col-sm-10").length;
  const testList = $(".edit-content>div>.col-sm-10");
  // 必填项 非空
  for (let i = 0; i < 2; ++i) {
    const conditionNull = $(".edit-content>div>.col-sm-10>.col-sm-4>input")
      .eq(i)
      .val();
    if (!conditionNull) {
      return;
    }
  }
  // 提示框中无has-error
  for (let i = 0; i < eqLength; ++i) {
    const condition = testList.eq(i).attr("class").includes("has-error");
    if (condition) {
      return;
    }
  }
  if ($("#startDate").val() > $("#endDate").val()) {
    $(".mod-start-date").addClass("has-error");
    $(".mod-end-date").addClass("has-error");
    return;
  }
  $("#addModal").modal("hide");
  // 下拉框值
  const option = $("#courseCategory option:selected").val();
  // console.log(`option`, option);
  // ？？？单选框值
  const radio = $(':radio[name="range"]:checked').val();
  console.log(`radio`, radio);
  // console.log(`radio`, $("input[name='courseRange']:checked").val());

  const addCourse = {
    trainingId: `${createId()}`,
    isSelected: false,
    trainingTitle: $("#courseTitle").val(),
    coverImage: $("#coverImage").val(),
    trainingCategory: `${option}`,
    startDate: $("#startDate").val(),
    endDate: $("#endDate").val(),
    numOfStudent: $("#numOfStudent").val(),
    trainingRange: radio,
    isFinished: false,
    // 可见范围
    // trainingData[index].visibleRange = ;
    trainingIntro: $("#courseIntro").val(),
  };
  trainingData.push(addCourse);
  renderTable(trainingData, currentPage);
});

/* 
  编辑页，点击 确认
  1. 校验信息
  2. 保存信息
  3. 渲染table
*/
function formValidation() {
  // 验证 1. courseTitle
  $("#modalBox").on("blur", "#courseTitle", function (event) {
    const value = $(event.target).val().trim();
    const name = $(event.target).attr("name");
    const rule = rules[name].contentReg;
    const contentErrorMessage = rules[name].contentErrorMessage;
    if (!rule.test(value)) {
      $(event.target).parent().next().text("");
      $(event.target).parent().parent().removeClass("has-error");
      $(event.target).parent().parent().addClass("has-success");
    } else {
      $(event.target).parent().next().text(`${contentErrorMessage}`);
      $(event.target).parent().parent().removeClass("has-success");
      $(event.target).parent().parent().addClass("has-error");
      return;
    }
  });
  // 验证 2. coverImage
  $("#modalBox").on(
    "change",
    ".edit-cover-image>div>div>input",
    function (event) {
      $(event.target).next().text("");
      const value = $(event.target).val();
      const name = $(event.target).attr("name");
      // 类型验证
      const rule = rules[name].contentReg;
      const contentErrorMessage = rules[name].contentErrorMessage;
      const tips = rules[name].tips;
      if (!value) {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${tips}`);
        $(event.target).parent().parent().addClass("has-error");
        return;
      } else if (rule.test(value)) {
        $(event.target).parent().next().text("");
        $(event.target).parent().parent().removeClass("has-error");
        $(event.target).parent().parent().addClass("has-success");
      } else {
        $(event.target).parent().next().text("");
        $(event.target).parent().next().text(`${contentErrorMessage}`);
        $(event.target).parent().parent().removeClass("has-success");
        $(event.target).parent().parent().addClass("has-error");
        return;
      }
    }
  );

  // 表单验证：？？？优化：封装
}
// function check(target) {
//   //
// }

// 点击 提交按钮

//补0函数
function getZeroPadding(num) {
  return num < 10 ? `0${num}` : num;
}
//格式化时间:
function formatDate(date) {
  let year = date.getFullYear();
  //月份+1，<10 补0
  let month = getZeroPadding(date.getMonth() + 1);
  //日期补0
  let day = getZeroPadding(date.getDate());
  //小时补0
  let hours = getZeroPadding(date.getHours());
  //分钟补0
  let minutes = getZeroPadding(date.getMinutes());
  //秒补0
  let seconds = getZeroPadding(date.getSeconds());
  return `${year}-${month}-${day}`;
}

// 数组去重
function arrayDeduplicate(arr, newArr) {
  const obj = {};
  for (let i = 0; i < arr.length; ++i) {
    const key = arr[i]; //遍历数组valueArr，将每个值作为obj 的key 值
    obj[key] = 1; //每个key 的value 赋1
  }
  for (let key in obj) {
    newArr.push(key); //遍历obj
  }
}
